﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Diagnostics;

namespace OPENXMLLib
{
    public class CodeNameResolver
    {
        public static void UpdateControlVersion(SpreadsheetDocument xDoc)
        {
            Sheet sheet = xDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(p => p.Name == "00-Control").SingleOrDefault();

            if (sheet == null)
            {
                return;
            }

            WorksheetPart worksheetPart = (WorksheetPart)xDoc.WorkbookPart.GetPartById(sheet.Id);
            if (worksheetPart == null)
            {
                return;
            }

            if (worksheetPart.Worksheet.SheetProperties == null)
            {
                worksheetPart.Worksheet.SheetProperties = new SheetProperties();
            }

            if (worksheetPart.Worksheet.SheetProperties.CodeName != null)
            {
                worksheetPart.Worksheet.SheetProperties.CodeName.InnerText = "CTRL" + DateTime.Now.ToString("yyMMddHHmmss");
            }
            else
            {
                worksheetPart.Worksheet.SheetProperties.CodeName = new DocumentFormat.OpenXml.StringValue("CTRL" + DateTime.Now.ToString("yyMMddHHmmss"));
            }

            Debug.WriteLine(string.Format("更新版本号为:{0}", worksheetPart.Worksheet.SheetProperties.CodeName.InnerText));

            worksheetPart.Worksheet.Save();
        }
        public static string GetControlVersion(SpreadsheetDocument xDoc)
        {
            Sheet sheet = xDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(p => p.Name == "00-Control").SingleOrDefault();

            if (sheet == null)
            {
                return string.Empty;
            }

            WorksheetPart worksheetPart = (WorksheetPart)xDoc.WorkbookPart.GetPartById(sheet.Id);
            if (worksheetPart == null)
            {
                return string.Empty;
            }

            if (worksheetPart.Worksheet.SheetProperties == null)
            {
                return string.Empty;
            }

            if (worksheetPart.Worksheet.SheetProperties.CodeName != null)
            {
                return worksheetPart.Worksheet.SheetProperties.CodeName.InnerText;
            }
            else
            {
                return string.Empty;
            }
        }
    }
}
